//
//  SearchResultViewController.m
//  TuiTe
//
//  Created by 张 霄鹤 on 10-6-4.
//  Copyright 2010 xhzhang. All rights reserved.
//

#import "SearchResultViewController.h"
#import "TwitterClient.h"
#import "Entry.h"
#import "User1.h"
#import "PImage.h"
#import "ProfileImageProcesser.h"

#import "UserInfoViewController.h"
#import "ViewControllerChooser.h"


@implementation SearchResultViewController

@synthesize searchType;
@synthesize searchKeyword;
@synthesize sb;
@synthesize renew;

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/


- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	
	searchResult = [[NSMutableArray alloc] init];
	nextPage = 1;
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	NSString *tt;
	if (renew) {
		@synchronized(self){
			[searchResult removeAllObjects];
			nextPage = 1;
			guessNext = NO;
		}
	}
	switch (searchType) {
		case ST_TWEET:
			tt = @"Search Tweet";
			break;
		case ST_USER:
			tt = @"Search User";
			break;
		case ST_TRENDS:
			tt = NSLocalizedString(@"TOPTEN",@"");
			if(searchKeyword){
				[NSThread detachNewThreadSelector:@selector(searchTweet:) toTarget:self withObject:searchKeyword];
			}

			break;
		default:
			tt = @"";
			break;
	}
	self.navigationItem.title = tt;
	[self.tableView reloadData];
	if (searchType == ST_TRENDS) {
		// iPhone 版本进行
		CGPoint newOffset = {0,44};
		[self.tableView setContentOffset:newOffset];
	}else {
		CGPoint newOffset = {0,0};
		[self.tableView setContentOffset:newOffset];
	}

}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
	renew = NO;
}

/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/

- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
	@synchronized(self){
		self.sb.text = @"";		
	}
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

#pragma mark -
#pragma mark SearchBarDelegateImpl

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
	[searchBar resignFirstResponder];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
	nextPage = 1;
	guessNext = NO;
	[searchBar resignFirstResponder];
	searchKeyword = searchBar.text;
#ifdef DEBUG
	NSLog(@"search text %@",searchKeyword);
#endif
	CGPoint newOffset = {0,44};
	[self.tableView setContentOffset:newOffset];
	
	[self startSearch];
}


- (void)startSearch{
	switch (searchType) {
		case ST_TWEET:
			if(searchKeyword){
				[NSThread detachNewThreadSelector:@selector(searchTweet:) toTarget:self withObject:searchKeyword];
			}
			break;
		case ST_USER:
			if(searchKeyword){
				[NSThread detachNewThreadSelector:@selector(searchUser:) toTarget:self withObject:searchKeyword];
			}
			break;
		default:
			break;
	}
}

#pragma mark -
#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger ret = [searchResult count];
	if (guessNext && searchType != ST_TRENDS) {
		ret += 1;
	}
	return ret;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
	
	cell.imageView.image = nil;
	cell.textLabel.text = nil;
	cell.detailTextLabel.text = nil;
	cell.accessoryType = UITableViewCellAccessoryNone;
	
    // Set up the cell...
	NSInteger row = indexPath.row;
	NSInteger sl = [searchResult count];
	if (row == sl) {
		// TODO Search Next
		cell.textLabel.text = @"Next Result";
	}else if (row < sl) {
	id obj = [searchResult objectAtIndex:row];
	if (obj) {
		if(searchType == ST_TWEET){
			// TODO 解析Tweet
			Entry *en = (Entry *)obj;
			cell.textLabel.text = en.content;
			cell.detailTextLabel.text = en.authName;
		}else if(searchType == ST_TRENDS){
			// TODO 解析
			Entry *en = (Entry *)obj;
			cell.textLabel.text = en.content;
			cell.detailTextLabel.text = en.authName;
		}else if(searchType == ST_USER){
			// TODO 解析User
			User1 *usr1 = (User1 *)obj;
			cell.textLabel.text = usr1.name;
			cell.detailTextLabel.text = usr1.screen_name;
			
			if (!usr1.following) {
				cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;   //  > 无圆框
			}else {
				cell.accessoryType = UITableViewCellAccessoryCheckmark;
			}

			
			
			ProfileImageProcesser *pp = [ProfileImageProcesser getInstance];
			pp.delegate = self;
			NSString *img = usr1.profile_image_url;
			if(img){			
				UIImage *im = [pp getImage:img];
				if(im){
					cell.imageView.image = im;
				}else{
					cell.imageView.image = pp.deflogo;
					[pp loadImage:img];
				}
			}
		}
	}
	}
	
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	NSInteger row = indexPath.row;
	NSInteger slen = [searchResult count];
	if (row == slen) {
		// TODO NextSearch
		[self startSearch];
	}else {

	id obj = [searchResult objectAtIndex:row];
	Entry *ent;
	User1 *user1;
	ViewControllerChooser *chooser;
	UserInfoViewController *uinfo;
	switch (self.searchType) {
		case ST_TWEET:
		case ST_TRENDS:
			// TODO Display Tweet Content
			ent = (Entry *)obj;
			break;
		case ST_USER:
			// TODO Display User Info
			user1 = (User1 *)obj;
			chooser = [ViewControllerChooser sharedChooser];
			uinfo = (UserInfoViewController *)[chooser choose:VC_USER_INFO];
			uinfo.user = user1;
			[self.navigationController pushViewController:uinfo animated:YES];
			break;
		default:
			break;
	}
	}
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark -
#pragma mark ImageLoad
- (void)imageDidLoadFinished:(NSString *)imgURL{
	[self.tableView reloadData];
}

#pragma mark -
#pragma mark implement METHOD

- (void)searchUser:(NSString *)n{
	TwitterClient *client = [TwitterClient getInstance];
	NSArray *usrs = [client doUserSearch:n withPage:nextPage];
	if(usrs){
		NSInteger tl = [usrs count];
		guessNext = tl >= 20;
		
		NSInteger sl = [searchResult count];
		if (sl == 0 || nextPage == 1) {
			[searchResult setArray:usrs];
		}else {
			[searchResult addObjectsFromArray:usrs];
		}
		nextPage++;
	}
	[self.tableView reloadData];
}

- (void)searchTweet:(NSString *)t{
	TwitterClient *client = [TwitterClient getInstance];
	
	NSArray *tweets = [client doSearch:t withPage:nextPage];
	if(tweets){
		
		NSInteger tl = [tweets count];
		guessNext = tl >= 15;
		//if (tl < 15) {
//			guessNext = NO;
//		}else {
//			guessNext = YES;
//		}

		NSInteger sl = [searchResult count];
		if (sl == 0 || nextPage == 1) {
			[searchResult setArray:tweets];
		}else {
			[searchResult addObjectsFromArray:tweets];
		}
		nextPage++;

		
		[self.tableView reloadData];
	}
}

#pragma mark -
#pragma mark MemoryManager

- (void)dealloc {
	[searchKeyword release];
	[searchResult release];
    [super dealloc];
}


@end

